package azalea.mqtt.gui.stream;

import java.io.IOException;
import java.io.InputStream;

import azalea.mqtt.message.utils.LengthUtil;
import azalea.mqtt.parse.data.CmdType;

public class MqttInputStream extends InputStream {
	static final int defaultLen = 102400;
	static final int magicInt = -9999;
	InputStream inputStream;
	byte[] streambuffer;
	int position;

	public MqttInputStream(InputStream instream, int capcity) {
		inputStream = instream;
		streambuffer = new byte[capcity];
		position = 0;
	}

	public MqttInputStream(InputStream instream) {
		this(instream, defaultLen);
	}

	@Override
	public int read() throws IOException {
		return inputStream.read();
	}

	public int readBytes(byte[] buffer) throws IOException {
		for (int i = 0; i < Integer.MAX_VALUE; ++i) {
			if (streambuffer.length - position < 1024) {
				throw new RuntimeException("buff overflow!,position:" + position);
			}
			int len = inputStream.read(streambuffer, position, streambuffer.length - position);
			if (len < 0) {
				return len;
			}
			position += len;
			int cmd = streambuffer[0] & 0xFF;
			cmd = cmd >> 4;
			CmdType cmdType = null;
			for (CmdType cType : CmdType.values()) {
				if (cType.getValue() == cmd) {
					cmdType = cType;
					break;
				}
			}
			if (cmdType == CmdType.PUBLISH) {
				int ret = handlePublish(buffer);
				if (ret != magicInt) {
					return ret;
				} else {
					continue;
				}
			}
			return handleDefault(buffer);
		}
		return -1;
	}

	private int handleDefault(byte[] buffer) {
		System.arraycopy(streambuffer, 0, buffer, 0, position);
		int tmp = position;
		position = 0;
		return tmp;
	}

	private int handlePublish(byte[] buffer) {
		// TODO Auto-generated method stub
		int[] pair = LengthUtil.parseLength(streambuffer, 1);
		int len = pair[0];
		if (position >= pair[0] + pair[1] + 1) {
			System.arraycopy(streambuffer, 0, buffer, 0, position);
			int tmp = position;
			position = 0;
			return tmp;
		}
		return magicInt;
	}
}
